package ma.zhiqiang.dataline.connector.transform;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import ma.zhiqiang.dataline.core.dto.SinkRecord;
import ma.zhiqiang.dataline.core.dto.SourceRecord;
import ma.zhiqiang.dataline.core.engine.Transform;

import java.util.List;
import java.util.Properties;

public class ReplaceTransform implements Transform {
    Properties properties;
    String template;                //需要替换的模板
    List<Variable> variables;       //需要替换的变量
    String replacedString;          //替换后的字符串

    public ReplaceTransform(Properties properties) {
        this.properties = properties;
        this.template = properties.getProperty("template");
        this.variables = JSONUtil.toList((JSONArray)properties.get("variables"),Variable.class);
    }

    @Override
    public SinkRecord transfer(SourceRecord sourceRecord) {
        replacedString = template;
        variables.stream().forEach(variable -> {
            replacedString.replace(variable.getVar(),sourceRecord.getColumn(variable.getAlias()).getValue().toString());
        });
        SinkRecord sinkRecord = new SinkRecord(replacedString);
        return sinkRecord;
    }
    @AllArgsConstructor
    @Data
    @NoArgsConstructor
    public static class Variable{
        String alias;
        String var;
    }
}
